package net.adst.ui.other;

import net.adst.beans.User;
import net.adst.resources.Constants;
import net.adst.resources.VariableNames;
import net.adst.util.DataManager;
import net.adst.util.GBC;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 29.11.12
 * Time: 3:44
 * To change this template use File | Settings | File Templates.
 */
public class EditPasswordDialog extends JDialog {
    private JLabel loginLabel;
    private JTextField loginField;

    private JLabel oldPasswordLabel;
    private JLabel newPasswordLabel;
    private JLabel new1PasswordLabel;

    private JPasswordField oldPasswordField;
    private JPasswordField newPasswordField;
    private JPasswordField new1PasswordField;

    private JButton saveButton;
    private JButton cancelButton;

    private User user;

    private JLabel statusLabel;

    public EditPasswordDialog(User user) {
        setLayout(new GridBagLayout());
        this.user = user;
        addElements();
    }

    private void addElements() {
        Dimension fieldDimension = new Dimension(100, 20);
        loginLabel = new JLabel("логин:");
        loginField = new JTextField(user.getLogin());
        loginField.setMaximumSize(fieldDimension);
        loginField.setPreferredSize(fieldDimension);
        loginField.setMinimumSize(fieldDimension);
        loginField.setEditable(false);
        oldPasswordLabel = new JLabel("Введите текущий пароль:");
        oldPasswordField = new JPasswordField();
        oldPasswordField.setMaximumSize(fieldDimension);
        oldPasswordField.setPreferredSize(fieldDimension);
        oldPasswordField.setMinimumSize(fieldDimension);
        newPasswordLabel = new JLabel("Введите новый пароль:");
        newPasswordField = new JPasswordField();
        newPasswordField.setMaximumSize(fieldDimension);
        newPasswordField.setPreferredSize(fieldDimension);
        newPasswordField.setMinimumSize(fieldDimension);
        new1PasswordLabel = new JLabel("Повторите новый пароль:");
        new1PasswordField = new JPasswordField();
        new1PasswordField.setMaximumSize(fieldDimension);
        new1PasswordField.setPreferredSize(fieldDimension);
        new1PasswordField.setMinimumSize(fieldDimension);
        saveButton = new JButton("сохранить");
        saveButton.setFocusPainted(false);
        cancelButton = new JButton("отмена");
        cancelButton.setFocusPainted(false);
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!user.getPassword().equals(String.valueOf(oldPasswordField.getPassword()))) {
                    statusLabel.setText("Введен неверный текущий пароль");
                    statusLabel.setForeground(Color.RED);
                    oldPasswordField.setText("");
                    oldPasswordField.requestFocusInWindow();
                    return;
                }
                if (String.valueOf(newPasswordField.getPassword()).equals(new1PasswordField.getPassword())) {
                    statusLabel.setText("Введеные пароли несовпадают");
                    statusLabel.setForeground(Color.RED);
                    newPasswordField.setText("");
                    new1PasswordField.setText("");
                    newPasswordField.requestFocusInWindow();
                    return;
                }
                if (String.valueOf(newPasswordField.getPassword()).isEmpty()) {
                    statusLabel.setText("Введите новый пароль");
                    statusLabel.setForeground(Color.RED);
                    newPasswordField.setText("");
                    new1PasswordField.setText("");
                    newPasswordField.requestFocusInWindow();
                    return;
                }
                try {
                    InputStream in = EditPasswordDialog.class.getClassLoader().getSystemResourceAsStream("info.xls");
                    HSSFWorkbook wb = null;
                    wb = new HSSFWorkbook(in);
                    ExcelExtractor extractor = new ExcelExtractor(wb);
                    extractor.setFormulasNotResults(false); // Считать формулы
                    HSSFSheet sheet = wb.getSheet("люди");
                    User newUser = null;
                    for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                        if (sheet.getRow(i) != null) {
                            if (sheet.getRow(i).getCell(1).toString().equalsIgnoreCase(user.getLogin())) {
                                sheet.getRow(i).getCell(2).setCellValue((String.valueOf(new1PasswordField.getPassword())).hashCode());
                                newUser = new User(user.getLogin(), new1PasswordField.getPassword().toString());
                                break;
                            }
                        }
                    }
                    DataManager.setObject(VariableNames.USER, newUser);
                    FileOutputStream fileOut = new FileOutputStream("d:\\adst\\adst\\src\\main\\resources\\info.xls");
                    wb.write(fileOut);
                    fileOut.close();
                    JOptionPane.showOptionDialog(null, "Изменение пароля прошло успешно", "парольбыл изменен", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
                    dispose();
                } catch (IOException e1) {
                    JOptionPane.showOptionDialog(null, "Нет доступа к базе данных. Проверьте соединени с сервером", "парольбыл не изменен", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                    dispose();
                }
            }
        });
        statusLabel = new JLabel();

        add(loginLabel, new GBC(0, 0).setInsets(5, 5).setAnchor(GBC.WEST));
        add(loginField, new GBC(1, 0).setInsets(5, 5).setAnchor(GBC.WEST));
        add(oldPasswordLabel, new GBC(0, 1).setInsets(5, 5).setAnchor(GBC.WEST));
        add(oldPasswordField, new GBC(1, 1).setInsets(5, 5).setAnchor(GBC.WEST));
        add(newPasswordLabel, new GBC(0, 2).setInsets(5, 5).setAnchor(GBC.WEST));
        add(newPasswordField, new GBC(1, 2).setInsets(5, 5).setAnchor(GBC.WEST));
        add(new1PasswordLabel, new GBC(0, 3).setInsets(5, 5).setAnchor(GBC.WEST));
        add(new1PasswordField, new GBC(1, 3).setInsets(5, 5).setAnchor(GBC.WEST));
        add(saveButton, new GBC(0, 4).setInsets(5, 5).setAnchor(GBC.CENTER));
        add(cancelButton, new GBC(1, 4).setInsets(5, 5).setAnchor(GBC.CENTER));
        add(statusLabel, new GBC(0, 5, 2, 1).setInsets(5, 5).setAnchor(GBC.CENTER));

    }

    public void init() {
        setDialogSettings();
        getContentPane().setBackground(Constants.COLOR_LIGHT_BLUE);
        setVisible(true);
    }

    private void setDialogSettings() {
        setModal(true);
        setModalityType(ModalityType.APPLICATION_MODAL);
        pack();
        setLocationRelativeTo(Frame.getFrames()[0]);
        setTitle("Изменить пароль.");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        getRootPane().setDefaultButton(saveButton);
    }

}
